//记录查询出的所有用户信息
var areaCenterobj=new Array();
//记录点击当前行的ID 修改信息使用
var areaCenterId;

Ext.onReady(function(){
	
	areaCenteriswriteidb= Ext.get('areaCenteriswriteid').getValue()==1?true:false;
	
	var areaCenterNameField=new Ext.form.NumberField({
		fieldLabel:'短信中心号',
		labelAlign:'right'
	});
	
	var areaCenterProvinceName=new Ext.form.ComboBox({
		fieldLabel:'省 份',
		labelAlign:'right',
		width:80,
		autoScroll:true,
		store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectsProvince.do',
            fields:['nAreaId','sName','sCode']
//            listeners:{
//           		load : function(stor,record,opts){
//           			areaCenterProvinceName.setValue(record[0].data.nAreaId);
//           			areaCenterCityName.clearValue();
//		           	areaCenterCityName.getStore().load({
//		           		params:{nProvinceId:areaCenterProvinceName.getValue()}
//		           	});
//           		}
//           	}
        }),
        hiddenValue:'sCode',
	    valueField:'nAreaId',
	    displayField:'sName',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
//        selectOnFocus:true,
//        editable:false,
        emptyText:'全 部',
        listeners:{
           select : function(combo, record,index)  {     
            areaCenterCityName.clearValue();
//            alert(areaCenterProvinceName.getValue());
           	areaCenterCityName.getStore().load({
           		params:{nProvinceId:areaCenterProvinceName.getValue()}
           	});
          }
       }
	});
	
	var areaCenterCityName=new Ext.form.ComboBox({
		fieldLabel:'城 市',
		labelAlign:'right',
		width:80,
		autoScroll:true,
        store: new Ext.data.JsonStore({
        	autoLoad:false,
            url:'selectsCitybyProvince.do',
            fields:['nAreaId','sName']
        }),
	    valueField:'nAreaId',
	    displayField:'sName',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        emptyText:'全 部',
        selectOnFocus:true,
        editable:false
	});
	
	var areaCenternOPField=new Ext.form.ComboBox({
		width:80,
		fieldLabel: '运营商',
	    store: new Ext.data.ArrayStore({
	        fields:['value','text'],
	        data:[
	         		[0, '全部'],
			        [1, '移动'],
			        [2, '联通']
		        ]
	    }),
	    mode:'local',
	    valueField:'value',
	    displayField:'text',
	    value:0,
	    editable:false,
	    triggerAction: 'all'
	});
	
	var areaCenterSearchBtn=new Ext.Button({
		text:'查询',
		handler:function(){
			areaCenterGridStore.load({
				params : {
					start : 0,
					limit : 20,
					'sName':areaCenterNameField.getValue()
				}
			});
		}
	});
	
	var areaCenterSearch=new Ext.Panel({
		height:70,
		region:'north',
		layout:'column',
		frame: true,
		border:false,
		bodyBorder:false,
		items:[
			{columnWidth:.27,layout:'form',labelAlign:'right',items:[areaCenterProvinceName,areaCenternOPField]},
			{columnWidth:.27,layout:'form',labelAlign:'right',items:[areaCenterCityName]},
			{columnWidth:.27,layout:'form',labelAlign:'right',items:[areaCenterNameField]},
			{columnWidth:.15,layout:'form',labelAlign:'right',items:[areaCenterSearchBtn]}]		
	});
	
	 areaCenterAddBtn =new Ext.Button({
		text:'添加短信中心',
		hidden:areaCenteriswriteidb,
		handler:function(){
			showareaCenterAddForm(1);
		}
	});
	
	 areaCenterGridStore = new Ext.data.Store({
        autoLoad: false,
        proxy : new Ext.data.HttpProxy({
            url: 'searchAreaCenter.do'
        }),
        baseParams:{sName: areaCenterNameField.getValue()},
        reader:new Ext.data.JsonReader({
             totalProperty: 'totalSize',
             root:'list'
        },[
            {name: 'ncenterNoRelAreaId',mapping:'ncenterNoRelAreaId', type: 'int'},
        	{name: 'scenterNo',mapping:'scenterNo', type: 'string'},
        	{name: 'sprovinceName',mapping:'sprovinceName', type: 'string'},
        	{name: 'scityName',mapping:'scityName', type: 'string'},
        	{name: 'nop',mapping:'nop', type: 'int'}
        ])
    });
    areaCenterGridStore.on("beforeload", function(thiz, options) {
		thiz.baseParams["sName"] = areaCenterNameField.getValue(); 
		thiz.baseParams["nprovinceId"] = areaCenterProvinceName.getValue();
		thiz.baseParams["ncityId"] = areaCenterCityName.getValue();
		thiz.baseParams["nop"] = areaCenternOPField.getValue();
	});
    
	var areaCenterGridBar=new Ext.PagingToolbar({
		store: areaCenterGridStore,
		displayInfo: true,
		pageSize:20,
		displayMsg : '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
		emptyMsg: "没有记录可以显示",
		beforePageText:'当前页码',
		afterPageText:'共{0}页', 
		firstText:'第一页', 
		prevText:'上一页', 
		nextText:'下一页', 
		lastText:'最后一页', 
		refreshText:'刷新当前页',
		items:['-', areaCenterAddBtn]
     });
     
	areaCenterGrid = new Ext.grid.GridPanel({
        store: areaCenterGridStore,
        region:'center',
        bodyBorder:false,
        stripeRows:true,
		disableSelection: true,
		border:false,
		frame:true,
		loadMask :{msg:"数据加载中，请稍等..."},
		layout:'fit',
		viewConfig:{
			forceFit: true,
			scrollOffset:0
		},
        cm:new Ext.grid.ColumnModel([
        	new Ext.grid.RowNumberer(),
            {header: "标识", width:50, dataIndex: 'ncenterNoRelAreaId', sortable: true},
            {header: "短信中心号", flex: 1, dataIndex: 'scenterNo', sortable: true},
            {header: "省份",width:50, dataIndex: 'sprovinceName', sortable: true},
            {header: "城市",width:50, dataIndex: 'scityName', sortable: true},
            {header: "运营商", width:50, dataIndex: 'nop', sortable: true,
            	renderer:function(value){
            		if (value == 1) {
			            return '移动';
			        }else{
			        	return '联通';
			        }
            	}
            },
            {header: "操作", width:150,align:'center',sortable: true,
            	renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
			    	var areaCenterGridCrHtml='';
			    	areaCenterobj[record.data.ncenterNoRelAreaId]=record.json;
			    	if(areaCenteriswriteidb==false){
			    		areaCenterGridCrHtml='<a onclick="areaCenterGridColumnsRenderUplink('+record.data.ncenterNoRelAreaId+')" href="javascript:void(0)">修改</a>';
						areaCenterGridCrHtml+='<a style="margin-left:20px;margin-right:20px" onclick="roleGridColumnsRenderDellink('+record.data.ncenterNoRelAreaId+')" href="javascript:void(0)">删除</a>';	
			    	}
					return areaCenterGridCrHtml;
				}
            }
        ]),
        bbar: areaCenterGridBar
    });
    
    
	 var areaCenterMainPanel =new Ext.Viewport({
		layout:'border',
		renderTo:'areaCenterDIV',
		id:'areaCenterMainPanel',
		items:[areaCenterGrid,areaCenterSearch],
		listeners: {
	        'resize': function(viewport,adjWidth,adjHeight,rawWidth,rawHeight)  {
	          	Ext.getCmp("areaCenterMainPanel").setHeight((document.body.clientHeight - 290) * 0.67);  
			}
    	}
	});
});
	var areaCenterAddWin;
	var areaCenterAddNameField=new Ext.form.NumberField({
		allowBlank:false,
		fieldLabel: '短信中心号'
	});
	
	var areaCenterAddProvinceName=new Ext.form.ComboBox({
		fieldLabel:'省 份',
		labelAlign:'right',
		width:80,
		autoScroll:true,
		store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectsProvince.do',
            fields:['nAreaId','sName','sCode'],
            listeners:{
           		load : function(stor,record,opts){
           			areaCenterAddProvinceName.setValue(record[0].data.nAreaId);
           			areaCenterAddCityName.clearValue();
		           	areaCenterAddCityName.getStore().load({
		           		params:{nProvinceId:areaCenterAddProvinceName.getValue()}
		           	});
           		}
           	}
        }),
        hiddenValue:'sCode',
	    valueField:'nAreaId',
	    displayField:'sName',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
//        selectOnFocus:true,
        editable:false,
        listeners:{
           select : function(combo, record,index)  {     
            areaCenterAddCityName.clearValue();
           	areaCenterAddCityName.getStore().load({
           		params:{nProvinceId:areaCenterAddProvinceName.getValue()}
           	});
          }
       }
	});
	
	var areaCenterAddCityName=new Ext.form.ComboBox({
		fieldLabel:'城 市',
		labelAlign:'right',
		width:80,
		autoScroll:true,
        store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectsCitybyProvince.do',
            fields:['nAreaId','sName','sCode']
        }),
	    valueField:'nAreaId',
	    displayField:'sName',
	    hiddenValue:'sCode',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        emptyText:'全 部',
        selectOnFocus:true,
        editable:false
	});
	
	var areaCenterAddnOPField=new Ext.form.ComboBox({
		width:80,
		fieldLabel: '运营商',
	    store: new Ext.data.ArrayStore({
	        fields:['value','text'],
	        data:[
			        [1, '移动'],
			        [2, '联通']
		        ]
	    }),
	    mode:'local',
	    valueField:'value',
	    displayField:'text',
	    value:1,
	    editable:false,
	    triggerAction: 'all'
	});
	
	//tinfo参数值1 :添加 2:修改
	function showareaCenterAddForm(tinfo,areaCenterJson) {
        if (!areaCenterAddWin) {
            areaCenterAddform = new Ext.FormPanel({
                border: false,
                labelAlign:'right',
                frame:true,
                items: [
                	areaCenterAddProvinceName,areaCenterAddCityName,
                	areaCenterAddnOPField,areaCenterAddNameField
                ],
                buttons: [{
                    text: '确 认',
                    handler: function() {
                    	
                    	if(!areaCenterAddNameField.validate()){
                    		return ;
                    	}
                    	if(this.text=='添 加'){
                    		
                    		if(areaCenterAddProvinceName.getRawValue()=='默认'){
                    			Ext.Msg.alert("信息!","请选择省份"); 
		                		return ;
                    		}
                    		
                    		if(areaCenterAddCityName.getValue()==''||areaCenterAddCityName.getRawValue()=='全部'){
		                		Ext.Msg.alert("信息!","请选择城市"); 
		                		return ;
		                	}
		                	
                    		var provinceIndex=areaCenterAddProvinceName.selectedIndex<0?0:areaCenterAddProvinceName.selectedIndex;
		                	var provinceStore=areaCenterAddProvinceName.getStore();
		                	var provinceScode=provinceStore.data.items[provinceIndex].json.sCode;
		                	var cityScode='';
	                		var cityIndex=areaCenterAddCityName.selectedIndex<0?0:areaCenterAddCityName.selectedIndex;
		                	var cityStore=areaCenterAddCityName.getStore();
		                	cityScode=cityStore.data.items[cityIndex].json.sCode;
                	
                    		Ext.Ajax.request({
								url:'addAreaCenter.do',
								method:'POST',
								params : {
				                   scenterNo:areaCenterAddNameField.getValue(),
				                   sprovinceName:areaCenterAddProvinceName.getRawValue(),
				                   sprovinceCode:provinceScode,
				                   nprovinceId:areaCenterAddProvinceName.getValue(),
				                   scityName:areaCenterAddCityName.getRawValue(),
				                   scityCode:cityScode,
				                   ncityId:areaCenterAddCityName.getValue(),
				                   nop:areaCenterAddnOPField.getValue()
				                }, 
				  				success: function (response) {
	
				  					if(response.responseText=='true'){
			                            Ext.MessageBox.alert('信息!', '添加成功!');
			                            areaCenterAddform.getForm().reset();
			                            areaCenterAddWin.hide();
			                            areaCenterGridStore.reload();
				  					}
				  					else{
				  						Ext.Msg.alert("Error","添加信息失败！"); 
				  					}
				              	}, 
				  				failure: function (response) {
				                    Ext.Msg.alert("Error","错误"); 
				            	}
							});
                    	}else if(this.text=='修 改'){
                    		Ext.Ajax.request({
								url:'updateAreaCenter.do',
								method:'POST',
								params : {
								   ncenterNoRelAreaId : areaCenterId,
				                   scenterNo:areaCenterAddNameField.getValue(),
				                   nop:areaCenterAddnOPField.getValue()
				                }, 
				  				success: function (response) {
	
				  					if(response.responseText=='true'){
			                            Ext.MessageBox.alert('信息!', '修改成功!');
			                            areaCenterAddform.getForm().reset();
			                            areaCenterAddWin.hide();
			                            areaCenterGridStore.reload();
				  					}
				  					else{
				  						Ext.Msg.alert("Error","修改信息失败！"); 
				  					}
				              	}, 
				  				failure: function (response) {
				                    Ext.Msg.alert("Error","错误"); 
				            	}
							});
                    	}
                    	
                    	
                    }
                },{
                    text: '返 回',
                    handler: function() {
                    	areaCenterAddform.getForm().reset();
                    	areaCenterAddWin.hide();
                    }
                }]
            });

            areaCenterAddWin =new Ext.Window({
                title: '添加短信中心地市',
                closeAction: 'hide',
                width: 320,
                height: 200,
                layout: 'fit',
                resizable: true,
                modal: true,
                items: areaCenterAddform,
                listeners :{
	            	close:function(){
	            		areaCenterAddWin.getForm().reset();
	            	}
            }
            });
        }
        areaCenterAddWin.show();
        
        if(tinfo==2){
        	areaCenterAddWin.setTitle('修改短信中心地市 标识：'+areaCenterJson.ncenterNoRelAreaId);
    		areaCenterAddform.buttons[0].setText('修 改');
    		
    		areaCenterAddProvinceName.hide();
    		areaCenterAddCityName.hide();
    		
            areaCenterAddnOPField.setValue(areaCenterJson.nop);
            areaCenterAddNameField.setValue(areaCenterJson.scenterNo);
        }else{
        	areaCenterAddProvinceName.show();
        	areaCenterAddCityName.show();
        	areaCenterAddform.getForm().reset();
        	areaCenterAddWin.setTitle('添加短信中心地市 ');
    		areaCenterAddform.buttons[0].setText('添 加');
        }
    }
    
function areaCenterGridColumnsRenderUplink(ncenterNoRelAreaId){
	areaCenterId=ncenterNoRelAreaId;
	
	if(ncenterNoRelAreaId){
		showareaCenterAddForm(2,areaCenterobj[ncenterNoRelAreaId]);
	}
}

function roleGridColumnsRenderDellink(ncenterNoRelAreaId){
	
	Ext.MessageBox.confirm('信息', '是否确认删除短信中心号 标识： '+ncenterNoRelAreaId+'?', function(btn){
		
		if(btn=='yes'){
			Ext.Ajax.request({
				url:'deleteAreaCenter.do',
				method:'POST',
				params:{
					ncenterNoRelAreaId:ncenterNoRelAreaId
				},
				success:function(response){
					if(response.responseText=='true'){
						Ext.MessageBox.alert('信息','删除成功！');
						areaCenterGridStore.reload();
					}else{
						Ext.MessageBox.alert('ERROR','删除失败！');
					}
				},
				failure:function(){
					Ext.Msg.alert('ERROR','错误');
				}
			});
		}
	});
}